/*
 *  您可以更改此项目但请不要删除作者署名谢谢，否则根据中华人民共和国版权法进行处理.
 *  You may change this item but please do not remove the author's signature,
 *  otherwise it will be dealt with according to the Copyright Law of the People's Republic of China.
 *
 *  yangbuyi Copyright (c) https://yby6.com 2024.
 */

import { defineStore } from 'pinia'


export const useChatStore =
  defineStore('chatStore', () => {

    // 定义消息集合
    const messageList = ref([])
    // 定义消息排序
    const index = ref(0)
    // 存储智能体数据
    const agentData = ref({
      "assistantId": "pCwCLmfl48p7",
      "name": "小朋友的故事屋",
      "description": "小朋友的故事屋可以根据需要的主题生成出图文故事",
      "logo": "https://hunyuan-base-prod-1258344703.cos.ap-guangzhou.myqcloud.com/hunyuan_open/agentlogo/091b2322d19771cda94eccee62f03fa9.png",
      "to": "https://yuanqi.tencent.com/agent/pCwCLmfl48p7?from=share&shareId=TK5rN7MMKrQy"
    })


    /**
     * 新增消息集合
     * @param message
     */
    const pushMessage = (message) => {
      console.log(message);
      messageList.value.push(message)
      console.log(messageList.value);
    }

    /**
     * 获取最后一条消息
     * @returns {number}
     */
    const getLastIndex = () => {
      return messageList.value.length
    }

    /**
     * 叠加排序
     */
    const addIndex = () => {
      index.value = index.value + 1
      return index.value
    }


    /**
     * 格式化消息
     * @param messages 消息
     */
    const formatMessages = (messages) => {
      // 如果历史消息超过5，只取最新的3个 获取最新的三个消息，如果 messages 长度小于等于 3，则返回全部消息
      // const latestMessages = messages.length > 3 ? messages.slice(-4) : messages; //
      // console.log(latestMessages); .filter(f => f.text !== '#' || f.stream != null)
      return messages.filter(f => f.text !== '#').map(item => ({
        role: item.isUser ? "user" : "assistant",
        content: [
          {
            type: "text",
            text: item.text
          }
        ]
      }))
    }

    /**
     * 更新指定消息文本达到流试
     * @param messageList 当前消息集合
     * @param reader 文本
     * @param stream 是否开启
     * @param speed 流试
     */
    const updateMessage = (messageList, reader, stream = false, speed = 50) => {
      try {
        if (stream) {
          // 在 reader 提取 Markdown 图片并存储到集合
          const markdownImgRegex = /!\[(.*?)\]\((.*?)\)/g;
          const markdownImages = [];
          let match;
          while ((match = markdownImgRegex.exec(reader)) !== null) {
            // 将Markdown图片链接添加到数组中
            markdownImages.push(match[0]);
          }
          console.log("img: ", markdownImages);

          // 清空 reader 当中的 markdown url
          reader = reader.replace(markdownImgRegex, "∮");

          console.log(reader);

          let i = 0
          messageList[messageList.length - 1].text = ""
          let printInterval = setInterval(() => {
            if (reader[i] === "∮") {
              messageList[messageList.length - 1].text += `${markdownImages.shift()}` ;
            } else {
              messageList[messageList.length - 1].text += reader[i];
            }
            i++
            if (i >= reader.length) {
              clearInterval(printInterval)
              i = 0
            }
          }, speed)
        } else {
          messageList[messageList.length - 1].text = reader
        }
      } catch (e) {
        console.error("流试报错: ",e)
        messageList[messageList.length - 1].text = reader
      }

    }

    /**
     * 存储智能体数据
     */
    const saveAgentData = (data) => {
      console.log("saveAgentData",data);
      agentData.value = data
    }

    /**
     * 获取当前智能体数据
     */
    const getAgentData = () => {
      return agentData.value
    }

    /**
     * 清空消息集合
     */
    const clearMessage = () => {
      messageList.value = []
    }

    return {
      messageList,
      index,
      agentData,
      getLastIndex,
      pushMessage,
      formatMessages,
      updateMessage,
      addIndex,
      saveAgentData,
      getAgentData,
      clearMessage
    };
  }, {
    persist: true
  });

export default useChatStore;
